<template>
    <span class="countdown">
        {{ days > 0 ? `${days}天` : '' }}
        {{ hours }}小时{{ minutes }}分{{ seconds }}秒
    </span>
</template>

<script>
export default {
    name: 'CountDown',
    props: {
        endTime: {
            type: [String, Number, Date],
            required: true
        },
        // 是否显示天数（当不足1天时自动隐藏）
        showDays: {
            type: Boolean,
            default: true
        },
        // 倒计时结束回调
        onFinish: {
            type: Function,
            default: null
        }
    },
    data() {
        return {
            now: Math.trunc(Date.now() / 1000),
            timer: null
        }
    },
    computed: {
        endTimestamp() {
            // 处理各种时间格式
            if (typeof this.endTime === 'string' || typeof this.endTime === 'number') {
                return Math.trunc(new Date(this.endTime).getTime() / 1000)
            }
            return Math.trunc(this.endTime.getTime() / 1000)
        },
        seconds() {
            return Math.trunc(this.diff) % 60
        },
        minutes() {
            return Math.trunc(this.diff / 60) % 60
        },
        hours() {
            return Math.trunc(this.diff / 60 / 60) % 24
        },
        days() {
            return Math.trunc(this.diff / 60 / 60 / 24)
        },
        diff() {
            return this.endTimestamp - this.now
        },
        isFinished() {
            return this.diff <= 0
        }
    },
    watch: {
        isFinished(newVal) {
            if (newVal) {
                this.$emit('finish')
                this.onFinish && this.onFinish()
                this.cleanTimer()
            }
        }
    },
    mounted() {
        this.startTimer()
    },
    beforeDestroy() {
        this.cleanTimer()
    },
    methods: {
        startTimer() {
            if (this.timer) return

            this.timer = setInterval(() => {
                this.now = Math.trunc(Date.now() / 1000)

                // 性能优化：倒计时结束后立即清除定时器
                if (this.isFinished) {
                    this.cleanTimer()
                }
            }, 1000)
        },
        cleanTimer() {
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
        },
        // 格式化时间，补零显示
        padTime(value) {
            return value < 10 ? `0${value}` : value
        }
    }
}
</script>

<style scoped>
.countdown {
    font-family: monospace;
    color: #f56c6c;
    font-weight: bold;
}
</style>